import 'base_generator.dart';

/// 服务生成器
class ServiceGenerator extends BaseGenerator {
  static void generate(String name, Map<String, dynamic> options) {
    if (!BaseGenerator.isValidName(name)) {
      BaseGenerator.printError('服务名称格式不正确: $name');
      return;
    }

    final String moduleName = options['module'] ?? '';
    final bool withApi = options['with-api'] == true;
    final bool withStorage = options['with-storage'] == true;

    final String className = BaseGenerator.toPascalCase(name);
    final String fileName = BaseGenerator.toSnakeCase(name);
    final String modulePath = BaseGenerator.getModulePath(moduleName);
    
    // 创建服务目录
    final String serviceDir = moduleName.isEmpty ? 
        'lib/shared/services' : '$modulePath/data/datasources';
    BaseGenerator.createDirectoryIfNotExists(serviceDir);
    
    // 生成服务文件
    final String servicePath = '$serviceDir/${fileName}_service.dart';
    final String serviceContent = _generateServiceContent(className, withApi, withStorage);
    
    BaseGenerator.writeFile(servicePath, serviceContent);
    
    BaseGenerator.printSuccess('服务', className, servicePath);
    _printUsageInstructions(className, withApi, withStorage);
  }

  static String _generateServiceContent(String className, bool withApi, bool withStorage) {
    String imports = '''
import 'package:get/get.dart';
''';

    if (withApi) {
      imports += '''
import 'package:dio/dio.dart';
import '../../core/network/dio_client.dart';
import '../../core/network/api_response.dart';
''';
    }

    if (withStorage) {
      imports += '''
import '../../core/storage/storage_service.dart';
''';
    }

    String mixinDeclaration = '';
    if (withStorage) {
      mixinDeclaration = ' with GetxServiceMixin';
    }

    String apiMethods = '';
    if (withApi) {
      apiMethods = '''

  // ================ API 方法 ================
  
  /// 获取数据列表
  Future<ApiResponse<List<Map<String, dynamic>>>> fetchList({
    int page = 1,
    int limit = 20,
    Map<String, dynamic>? filters,
  }) async {
    try {
      final queryParams = {
        'page': page,
        'limit': limit,
        if (filters != null) ...filters,
      };

      final response = await _dioClient.get(
        '$_apiPath',
        queryParameters: queryParams,
      );

      return ApiResponse.success(
        data: List<Map<String, dynamic>>.from(response.data['data'] ?? []),
        message: response.data['message'] ?? '获取成功',
      );
    } on DioException catch (e) {
      return ApiResponse.error(
        message: e.message ?? '网络请求失败',
        statusCode: e.response?.statusCode,
      );
    } catch (e) {
      return ApiResponse.error(message: '未知错误: \$e');
    }
  }

  /// 根据ID获取详情
  Future<ApiResponse<Map<String, dynamic>>> fetchById(String id) async {
    try {
      final response = await _dioClient.get('\$_apiPath/\$id');

      return ApiResponse.success(
        data: response.data['data'] as Map<String, dynamic>,
        message: response.data['message'] ?? '获取成功',
      );
    } on DioException catch (e) {
      return ApiResponse.error(
        message: e.message ?? '网络请求失败',
        statusCode: e.response?.statusCode,
      );
    } catch (e) {
      return ApiResponse.error(message: '未知错误: \$e');
    }
  }

  /// 创建新数据
  Future<ApiResponse<Map<String, dynamic>>> create(Map<String, dynamic> data) async {
    try {
      final response = await _dioClient.post(_apiPath, data: data);

      return ApiResponse.success(
        data: response.data['data'] as Map<String, dynamic>,
        message: response.data['message'] ?? '创建成功',
      );
    } on DioException catch (e) {
      return ApiResponse.error(
        message: e.message ?? '网络请求失败',
        statusCode: e.response?.statusCode,
      );
    } catch (e) {
      return ApiResponse.error(message: '未知错误: \$e');
    }
  }

  /// 更新数据
  Future<ApiResponse<Map<String, dynamic>>> update(
    String id,
    Map<String, dynamic> data,
  ) async {
    try {
      final response = await _dioClient.put('\$_apiPath/\$id', data: data);

      return ApiResponse.success(
        data: response.data['data'] as Map<String, dynamic>,
        message: response.data['message'] ?? '更新成功',
      );
    } on DioException catch (e) {
      return ApiResponse.error(
        message: e.message ?? '网络请求失败',
        statusCode: e.response?.statusCode,
      );
    } catch (e) {
      return ApiResponse.error(message: '未知错误: \$e');
    }
  }

  /// 删除数据
  Future<ApiResponse<bool>> delete(String id) async {
    try {
      final response = await _dioClient.delete('\$_apiPath/\$id');

      return ApiResponse.success(
        data: true,
        message: response.data['message'] ?? '删除成功',
      );
    } on DioException catch (e) {
      return ApiResponse.error(
        message: e.message ?? '网络请求失败',
        statusCode: e.response?.statusCode,
      );
    } catch (e) {
      return ApiResponse.error(message: '未知错误: \$e');
    }
  }

  /// 批量操作
  Future<ApiResponse<List<Map<String, dynamic>>>> batchOperation(
    String operation,
    List<String> ids,
  ) async {
    try {
      final response = await _dioClient.post(
        '\$_apiPath/batch',
        data: {
          'operation': operation,
          'ids': ids,
        },
      );

      return ApiResponse.success(
        data: List<Map<String, dynamic>>.from(response.data['data'] ?? []),
        message: response.data['message'] ?? '操作成功',
      );
    } on DioException catch (e) {
      return ApiResponse.error(
        message: e.message ?? '网络请求失败',
        statusCode: e.response?.statusCode,
      );
    } catch (e) {
      return ApiResponse.error(message: '未知错误: \$e');
    }
  }
''';
    }

    String storageMethods = '';
    if (withStorage) {
      storageMethods = '''

  // ================ 本地存储方法 ================
  
  /// 保存数据到本地
  Future<bool> saveToLocal(String key, dynamic data) async {
    try {
      await _storageService.write(key, data);
      return true;
    } catch (e) {
      print('保存到本地失败: \$e');
      return false;
    }
  }

  /// 从本地读取数据
  Future<T?> readFromLocal<T>(String key) async {
    try {
      return await _storageService.read<T>(key);
    } catch (e) {
      print('从本地读取失败: \$e');
      return null;
    }
  }

  /// 删除本地数据
  Future<bool> deleteFromLocal(String key) async {
    try {
      await _storageService.delete(key);
      return true;
    } catch (e) {
      print('删除本地数据失败: \$e');
      return false;
    }
  }

  /// 清除所有本地数据
  Future<bool> clearLocalData() async {
    try {
      await _storageService.clear();
      return true;
    } catch (e) {
      print('清除本地数据失败: \$e');
      return false;
    }
  }

  /// 检查本地是否存在指定数据
  Future<bool> hasLocalData(String key) async {
    try {
      return await _storageService.hasData(key);
    } catch (e) {
      print('检查本地数据失败: \$e');
      return false;
    }
  }

  /// 获取所有本地数据键
  Future<List<String>> getLocalKeys() async {
    try {
      return await _storageService.getKeys();
    } catch (e) {
      print('获取本地数据键失败: \$e');
      return [];
    }
  }

  /// 缓存数据（带过期时间）
  Future<bool> cacheData(
    String key,
    dynamic data, {
    Duration? expiration,
  }) async {
    try {
      final cacheData = {
        'data': data,
        'timestamp': DateTime.now().millisecondsSinceEpoch,
        'expiration': expiration?.inMilliseconds,
      };
      
      await _storageService.write('cache_\$key', cacheData);
      return true;
    } catch (e) {
      print('缓存数据失败: \$e');
      return false;
    }
  }

  /// 获取缓存数据
  Future<T?> getCachedData<T>(String key) async {
    try {
      final cacheData = await _storageService.read<Map<String, dynamic>>('cache_\$key');
      if (cacheData == null) return null;

      final timestamp = cacheData['timestamp'] as int;
      final expiration = cacheData['expiration'] as int?;
      
      // 检查是否过期
      if (expiration != null) {
        final now = DateTime.now().millisecondsSinceEpoch;
        if (now - timestamp > expiration) {
          await deleteFromLocal('cache_\$key');
          return null;
        }
      }

      return cacheData['data'] as T?;
    } catch (e) {
      print('获取缓存数据失败: \$e');
      return null;
    }
  }
''';
    }

    return BaseGenerator.generateFileHeader(
      className,
      '${className} - 数据服务层'
    ) + '''
$imports

class $className extends GetxService$mixinDeclaration {
${withApi ? '  late final DioClient _dioClient;' : ''}${withStorage ? '  late final StorageService _storageService;' : ''}${withApi ? '  static const String _apiPath = \'/${BaseGenerator.toKebabCase(className.replaceAll('Service', ''))}\';' : ''}

  @override
  void onInit() {
    super.onInit();
    _initService();
  }

  void _initService() {
${withApi ? '    _dioClient = Get.find<DioClient>();' : ''}${withStorage ? '    _storageService = Get.find<StorageService>();' : ''}    print('$className 初始化完成');
  }

  // ================ 核心业务方法 ================
  
  /// 初始化数据
  Future<void> initializeData() async {
    try {
      // 执行初始化逻辑
      print('$className 数据初始化开始');
      
      // 可以在这里执行数据预加载、配置检查等
      
      print('$className 数据初始化完成');
    } catch (e) {
      print('$className 数据初始化失败: \$e');
    }
  }

  /// 重置服务状态
  Future<void> reset() async {
    try {
${withStorage ? '      // 清除本地缓存\n      await clearLocalData();' : ''}      
      // 重置其他状态
      
      print('$className 重置完成');
    } catch (e) {
      print('$className 重置失败: \$e');
    }
  }

  /// 健康检查
  Future<bool> healthCheck() async {
    try {
${withApi ? '''      // 检查API连接
      final apiResponse = await _dioClient.get('/health');
      if (apiResponse.statusCode != 200) return false;
''' : ''}${withStorage ? '''      // 检查存储服务
      final storageTest = await _storageService.write('health_check', 'test');
      await _storageService.delete('health_check');
''' : ''}      
      return true;
    } catch (e) {
      print('$className 健康检查失败: \$e');
      return false;
    }
  }$apiMethods$storageMethods

  @override
  void onClose() {
    // 清理资源
    print('$className 服务关闭');
    super.onClose();
  }
}
''';
  }

  static void _printUsageInstructions(String className, bool withApi, bool withStorage) {
    print('\n📋 使用说明:');
    
    print('1. 注册服务:');
    print('   // 在main.dart中');
    print('   Get.putAsync(() async => $className());');
    print('');
    print('2. 获取服务实例:');
    print('   final service = Get.find<$className>();');
    print('');
    print('3. 在控制器中使用:');
    print('   class YourController extends GetxController {');
    print('     late final $className _service;');
    print('     ');
    print('     @override');
    print('     void onInit() {');
    print('       _service = Get.find<$className>();');
    print('       super.onInit();');
    print('     }');
    print('   }');

    if (withApi) {
      print('');
      print('4. API调用示例:');
      print('   // 获取列表');
      print('   final response = await service.fetchList();');
      print('   if (response.isSuccess) {');
      print('     final data = response.data;');
      print('   }');
      print('   ');
      print('   // 创建数据');
      print('   final createResponse = await service.create({');
      print('     \'name\': \'示例名称\',');
      print('     \'description\': \'示例描述\',');
      print('   });');
    }

    if (withStorage) {
      print('');
      print('5. 本地存储示例:');
      print('   // 保存数据');
      print('   await service.saveToLocal(\'user_data\', userData);');
      print('   ');
      print('   // 读取数据');
      print('   final userData = await service.readFromLocal(\'user_data\');');
      print('   ');
      print('   // 缓存数据');
      print('   await service.cacheData(\'temp_data\', data, ');
      print('     expiration: Duration(hours: 1));');
    }

    print('');
    print('6. 依赖注入顺序:');
    if (withApi) {
      print('   - DioClient (网络客户端)');
    }
    if (withStorage) {
      print('   - StorageService (存储服务)');
    }
    print('   - $className (当前服务)');
  }
}
''';
  }
}